<?php


use App\Library\Utils\Arr;
use Phinx\Seed\AbstractSeed;
use Faker\Factory as FakerFactory;

class CoursePackageSeeder extends AbstractSeed
{
    public function getDependencies(): array
    {
        return [
            'CourseSeeder',
            'PackageSeeder',
        ];
    }

    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * https://book.cakephp.org/phinx/0/en/seeding.html
     */
    public function run()
    {
        $faker = FakerFactory::create('zh_CN');

        $courses = $this->fetchAll('SELECT * FROM kg_course');
        $packages = $this->fetchAll('SELECT * FROM kg_package');

        $rows = [];
        for ($i = 0; $i < 1000; $i++) {
            $course = Arr::rand($courses);
            $package = Arr::rand($packages);
            $rows[] = [
                'course_id' => $course['id'],
                'package_id' => $package['id'],
                'create_time' => $faker->unixTime,
            ];
        }
        $this->table('kg_course_package')->insert($rows)->saveData();

        // update course
        $coursePackages = $this->fetchAll('SELECT course_id, COUNT(*) AS count FROM kg_course_package GROUP BY course_id');
        foreach ($coursePackages as $cp) {
            $count = $cp['count'];
            $id = $cp['course_id'];
            $this->execute("UPDATE kg_course SET package_count={$count} WHERE id={$id}");
        }

        // update package
        $coursePackages = $this->fetchAll('SELECT package_id, COUNT(*) AS count FROM kg_course_package GROUP BY package_id');
        foreach ($coursePackages as $cp) {
            $count = $cp['count'];
            $id = $cp['package_id'];
            $this->execute("UPDATE kg_package SET course_count={$count} WHERE id={$id}");
        }
    }

}
